package com.cicadamob.contact.api.group.asynctask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.ImageUtil;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Logger.AppLogger;
import com.cicadamob.contact.api.Utils.NetWork.HttpRequestCallBack;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil;
import com.cicadamob.contact.api.Utils.NetWork.NetWorkUtil;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil.RequestMethod;
import com.cicadamob.contact.api.Utils.pinyin.LetterParser;
import com.cicadamob.contact.api.group.bean.Group;
import com.cicadamob.contact.api.group.bean.ResultModel;
import com.cicadamob.contact.api.group.dao.Group_Db_Dao;
import com.cicadamob.contact.api.group.http.Http_Group_Util;
import com.cicadamob.contact.api.service.Contact;
import com.cicadamob.contact.api.service.ServerUrl;
import com.cicadamob.contact.api.service.AppDbHelper.TS_GROUP_NAME;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
/**
 * 编辑群组
 * @author 
 *
 */
public class EditGroupRunnable implements Runnable{
	private Handler mHandler;
	private int what;
	private Context context;
	private String groupName;
	private String groupImagePath;
	private String groupId;
	private Group_Db_Dao db_dao;
	public EditGroupRunnable(Handler mHandler, int what, Context context,
			String groupName, String groupImagePath,String groupId) {
		super();
		this.mHandler = mHandler;
		this.what = what;
		this.context = context;
		this.groupName = groupName;
		this.groupImagePath = groupImagePath;
		this.groupId=groupId;
		db_dao=Group_Db_Dao.getInstance(context);
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		ResultModel resultMode = new ResultModel();
		if (!NetWorkUtil.isConnected(context)) {
			resultMode.setRetcode(100);
			sendMessage(resultMode);
			return ;// 网络异常
		}
		
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String imageInfo="";
				if(!StringUtil.isEmpty(groupImagePath)){
					imageInfo=ImageUtil.ImageToBase64Str(groupImagePath);
				}
			   	String xmlstr=Http_Group_Util.get_modPersonalGroupXML(groupId, groupName, "", imageInfo);
			    Map<String, String>  requestMap=new HashMap<String,String>();
			    requestMap.put(HttpUtil.XML, xmlstr);
			    AppLogger.writeLogToFile(context, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "发送报文  url =" + ServerUrl.MOD_PERSONAL_GROUP
			    		+"\r\n xml ="+xmlstr, true);	
			   	HttpUtil.HttpRequest(context, RequestMethod.POST, ServerUrl.MOD_PERSONAL_GROUP, requestMap, new HttpRequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						doSuccess(responseInfo.result);
						AppLogger.writeLogToFile(context, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "响应报文  url =" + ServerUrl.MOD_PERSONAL_GROUP
					    		+"\r\n xml ="+responseInfo.result, true);	
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						doFailure(error, msg);
					}
				});
			}
		});
		
		

	
	}
	
	private void sendMessage(ResultModel resultModel){
		mHandler.obtainMessage(what, resultModel).sendToTarget();
	}
	/**
	 * 处理请求成功
	 * @param result
	 */
	private void doSuccess(String result){

		ResultModel resultModel = Http_Group_Util.parseResult(result);
		if (resultModel.getRetcode() != 0) {//失败
				sendMessage(resultModel);

		} else { // 编辑成功
			//修改本地库 组名
			String[] spells=LetterParser.getSpells(groupName);
			
			ContentValues values=new ContentValues();
			values.put(TS_GROUP_NAME.GROUP_NAME, groupName);
            
			values.put(TS_GROUP_NAME.QPNAME, spells[0]);
			values.put(TS_GROUP_NAME.SPNAME, spells[1]);
			if(!StringUtil.isEmpty(resultModel.getImagePath())){
				values.put(TS_GROUP_NAME.IMAGEPATH, resultModel.getImagePath());
			}
			
			//发送广播通知  群组消息更新相关信息
			Group group=new Group();
	    	group.setGroup_id(groupId);
	    	group.setGroup_name(groupName);
	    	if(!StringUtil.isEmpty(resultModel.getImagePath())){
	    		group.setImagePath(resultModel.getImagePath()); 
			}
	    	//PushUtils.MsgSyncGroupOrMember(instance, 1, group, null,null);
			
			
			db_dao.updateGroupById(values, groupId);
			
			Intent it=new Intent();
			it.putExtra("groupName", groupName);
			((Activity) context).setResult(Activity.RESULT_OK, it);
			sendMessage(resultModel);
			//======暂时屏蔽
		       /* PushMessageModel message=new PushMessageModel();
		        message.setGroupName(et_groupName.getText().toString());
		        String tip=PushUtils.getNoticeTips(6, message);
	    	PushUtils.MsgSyncGroupOrMember(instance, 1, group,null, tip,false);*/
			//==========================================
		}

		
	
	}
	
	/**
	 * 处理请求失败
	 * @param error
	 * @param msg
	 */
	private void doFailure(HttpException error, String msg){
		ResultModel resultMode = new ResultModel();
		resultMode.setRetcode(-9);
		sendMessage(resultMode);
	}
			
}
